package vip.afeng.screen;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;

public class GuiCamera {

    private String fileName;
    private String defaultName = "GuiCamera";

    static int serialNum = 0;

    private String imageFormat;//图像文件的格式
    private String defaultImageFormat = "jpg";

    private Robot robot = null;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    private int width = screenSize.width -20;
    private int heigt = screenSize.height -50;
    private Rectangle rectangle = new Rectangle(10, 10, width, heigt);

    public GuiCamera() {
        fileName = defaultName;
        imageFormat = defaultImageFormat;
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public GuiCamera(String s, String format) {
        fileName = s;
        imageFormat = format;
    }

    /**
     * 对屏幕进行拍照
     **/
    public byte[] snapshot() {
        try {
            //拷贝屏幕到一个BufferedImage对象screenshot
//            BufferedImage screenshot = robot.createScreenCapture(rectangle);
//            BufferedImage back = (new Robot()).createScreenCapture(
//                    new Rectangle(0, 0, (int) screenSize.getWidth(), (int) screenSize.getHeight()));
//            serialNum++;
            //根据文件前缀变量和文件格式变量，自动生成文件名
//            String name = fileName + String.valueOf(serialNum) + "." + imageFormat;
//            System.out.print(serialNum);
//            File f = new File(name);
//            System.out.println("Save File-" + name);
            //将screenshot对象写入图像文件

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(robot.createScreenCapture(rectangle), imageFormat, out);
            return out.toByteArray();

//            ImageIO.write(screenshot, imageFormat, f);

//            System.out.println("..Finished");

        } catch (Exception e) {
            System.out.println(e);
        }
        return new byte[0];
    }

    public static void main(String[] args) {
        //"C:\\sally\\bootstrap栅格"是根据自己随意找的一个图片形式，"png"是图片的格式
//        GuiCamera cam = new GuiCamera("C:\\sally\\bootstrap栅格", "png");

//        cam.snapshot();
        GuiCamera guiCamera = new GuiCamera();
        byte[] snapshot = guiCamera.snapshot();
        System.out.println("snapshot = " + new String(snapshot));

    }
}